<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
include 'imex.php';

class User extends CI_Controller {

    function __construct() {
        parent::__construct();
        if (!$this->session->userdata('logged_in'))
            redirect("login");
        if (isAdmin())
            redirect('admin');
        $this->load->library('form_validation');
        $this->load->model('user_model');
        $this->load->model('admin_model');
        $this->load->model('login_model');
    }

    function index() {
        $this->calendar();
    }

    /**
     * Zakladne vykreslenie interface pre uzivatela. 
     * Metoda podla datumov a pouzivatelov vykresli kalendar
     * na tyzdennej
     */
    function calendar() {
        $sess_step = $this->session->userdata('step');

        if (isset($_POST['reset'])) {
            $step = 0;
            $this->session->unset_userdata('selected_departments');
            $this->session->unset_userdata('selected_users');
            $_POST['date'] = "";
            $this->session->set_userdata('conds', array());
        } else if (isset($_POST['submit_department'])) {
            $step = 1;
        } else if (isset($_POST['submit_user'])) {
            if (empty($_POST['user'])) {
                $step = 1;
            } else {
                $step = 2;
            }
        } else if (isset($_POST['edit_department'])) {
            $step = 0;
            $this->session->unset_userdata('selected_users');
        } else if (isset($_POST['edit_user'])) {
            $step = 1;
        } else if (!empty($sess_step)) {
            $step = $this->session->userdata('step');
        } else {
            $step = 0;
        }
        $this->session->set_userdata("step", $step);

        if (isset($_POST["date"]) AND (!empty($_POST["date"]))) {
            $dates = getRegularDate(week_from_monday($_POST["date"]));
        } else {
            $dates = getRegularDate(week_from_monday(date('d-m-Y')));
        }
        $dates_session = array(0 => changeFormatDate($dates[0]), 1 => changeFormatDate($dates[4]));
        $this->session->set_userdata("date", $dates_session);


        for ($i = 5; $i < 10; $i++)
            $dates[$i] = strval($i - 4);

        if (isset($_POST['user'])) {
            $conds['users'] = $_POST['user'];
            $conds['users'][] = $this->session->userdata('user_id');
            $this->session->set_userdata("selected_users", $_POST['user']);
        } else {
            $conds_session = $this->session->userdata('conds');
            if (!empty($conds_session)) {
                $conds = $this->session->userdata('conds');
            } else {
                $conds['users'] = array(0 => $this->session->userdata('user_id'));
            }
        }

        $this->session->set_userdata("conds", $conds);

        $conds2 = "";
        if (isset($_POST['department'])) {
            $conds2['department'] = $_POST['department'];
            $this->session->set_userdata('selected_departments', $_POST['department']);
        } else {
            $departments_session = $this->session->userdata('selected_departments');
            if (!empty($departments_session)) {
                $conds2['department'] = $departments_session;
            }
        }

        $users = array();
        if (isset($conds2['department']) && !empty($conds2['department'])) {
            if (strcmp($conds2['department'][0], 'Všetky') == 0) {
                $users = $this->admin_model->getUsers(array());
            } else {
                $users = $this->admin_model->getUsers($conds2);
            }
        } else {
            $users = $this->admin_model->getUsers(array());
        }

        $data = array('events' => $this->user_model->getEvents($conds),
            'users' => $users,
            'dates' => $dates,
            'departments' => $this->admin_model->getDepartments(),
            'step' => $this->session->userdata('step'),
            'select_departments' => $this->session->userdata('selected_departments'),
            'select_users' => $this->session->userdata('selected_users'),
            'select_users_names' => getNames($this->session->userdata('selected_users'))
        );

        $data['departments'][0] = array('department' => "Všetky");

        if (isset($_POST['date'])) {
            $data['date'] = $_POST['date'];
        }



        $this->template->set('title', 'SKaP - kalendár');
        $this->template->view("skap", $data);
    }

    /**
     * Vykreslenie dat pouzivatela do tabulky
     * podla zadanych parametrov 
     */
    function table() {
        $conds['users'] = array(0 => $this->session->userdata('user_id'));


        $data = array('events' => $this->user_model->getEvents($conds));

        $this->template->set('title', 'SKaP - tabuľka');
        $this->template->view("table_view", $data);
    }

    /**
     * metoda sluziaca na pridanie eventu, polia formularu su okontrolovane, 
     * ak splnaju poziadavky, data su poslane modelu.
     * 
     */
    function addevent() {
        $data['types'] = $this->user_model->getEventTypes();
        $data['types'][] = array('id' => 0, 'event_type' => "Nová");        

        $data['rooms'] = $this->user_model->getRooms();

        $this->form_validation->set_rules('event_meno', 'meno', 'trim|required|xss_clean');

        if ($this->form_validation->run()) {
            $date = "";
            switch ($_POST["typ"]) {
                case 1: $date = $_POST["den"];
                    break;
                default: $date = $_POST["rok"] . "-" . addZeroToDate($_POST["mesiac"]) . "-" . addZeroToDate($_POST["datum"]);
            };

            $input = array(
                'user_id' => $this->session->userdata('user_id'),
                'event' => array(
                    'description' => $_POST["event_meno"],
                    'event_type' => $_POST["typ"],
                    'event_day' => $date,
                    'start_time' => ($_POST["od_hod"] * 60) + $_POST["od_min"],
                    'end_time' => ($_POST["do_hod"] * 60) + $_POST["do_min"],
                    'room_id' => $_POST['room'])
            );

            if ($input['event']['end_time'] - $input['event']['start_time'] <= 0) {
                $data['mess'] = "Zadali ste nesprávne trvanie eventu";
                $this->template->set('title', 'SKaP - pridať udalosť');
                $this->template->view("addevent_form", $data);
                return;
            }

            if ($input['event']['event_type'] == 0) {
                $input['event']['event_type'] = $this->user_model->addEventType($_POST['nove']);
                $data['types'] = $this->user_model->getEventTypes();
                $data['types'][] = array('id' => 0, 'event_type' => "Nová");
            }
            if ($this->user_model->addEvent($input))
                $data['mess'] = "Event bol úspešne pridaný!";
            else
                $data['mess'] = "Event NEbol úspešne pridaný! Skuste ho pridať znova, alebo kontaktujte admina.";
            $this->template->set('title', 'SKaP - pridať udalosť');
            $this->template->view("addevent_form", $data);
        } else {
            $this->template->set('title', 'SKaP - pridať udalosť');
            $this->template->view("addevent_form", $data);
        }
    }

    /**
     * metoda sluzi na editaciu existujuceho eventu
     * @param type $id id eventu ktory sa bude upravovat
     * @return type 
     */
    function editevent($id = "") {
        if (!isset($id))
            redirect('user');
        $this->form_validation->set_rules('event_meno', 'meno', 'trim|required|xss_clean');
        $input = array(
            'event_id' => array(0 => $id),
            'users' => array(0 => $this->session->userdata('user_id'))
        );
        $event = $this->user_model->getEvents($input);
        if (!$event)
            redirect('user');
        $od_time = explode(':', getStringTimeFromMinutes($event[0]["start_time"]));
        $do_time = explode(':', getStringTimeFromMinutes($event[0]["end_time"]));
        if (strlen($event[0]['event_day']) > 1) {
            $date = explode('-', getNormalDate($event[0]['event_day']));
        } else {
            $date = explode('-', $event[0]['event_day']);
        }
        $val = array(
            'event_meno' => $event[0]["description"],
            'typ' => $event[0]["event_type"],
            'room' => $event[0]["room_id"],
            'od_hod' => $od_time[0],
            'od_min' => $od_time[1],
            'do_hod' => $do_time[0],
            'do_min' => $do_time[1],
            'datum' => isset($date[0]) ? $date[0] : "",
            'mesiac' => isset($date[1]) ? $date[1] : "",
            'rok' => isset($date[2]) ? $date[2] : date("Y"),
            'den' => $event[0]['event_day']
        );

        $data['val'] = $val;
        $data['types'] = $this->user_model->getEventTypes();
        $data['rooms'] = $this->user_model->getRooms();
        $data['id'] = $id;


        if ($this->form_validation->run()) {
            $date = "";
            switch ($_POST["typ"]) {
                case 1: $date = $_POST["den"];
                    break;
                case 2:;
                case 3: $date = $_POST["rok"] . "-" . addZeroToDate($_POST["mesiac"]) . "-" . addZeroToDate($_POST["datum"]);
            };
            $input = array(
                'event_id' => $id,
                'event' => array(
                    'description' => $_POST["event_meno"],
                    'event_type' => $_POST["typ"],
                    'event_day' => $date,
                    'start_time' => ($_POST["od_hod"] * 60) + $_POST["od_min"],
                    'end_time' => ($_POST["do_hod"] * 60) + $_POST["do_min"],
                    'room_id' => $_POST['room'])
            );

            if ($input['event']['end_time'] - $input['event']['start_time'] <= 0) {
                $data['mess'] = "Zadali ste nesprávne trvanie eventu";
                $this->template->set('title', 'SKaP - pridať udalosť');
                $this->template->view("edit_event", $data);
                return;
            }
            if ($this->user_model->editEvent($input))
                $data['mess'] = "Event bol úspešne aktualizovaný!";
            else
                $data['mess'] = "Event NEbol úspešne aktualizovaný! Skuste ho pridať aktualizovať, alebo kontaktujte admina.";
            $this->template->set('title', 'SKaP - editovať udalosť');
            $this->template->view("edit_event", $data);
        } else {
            $this->template->set('title', 'SKaP - editovať udalosť');
            $this->template->view("edit_event", $data);
        }
    }

    /**
     * Metoda vymaze event podla id
     * @param type $id id eventu ktory cheme vymazat
     */
    function deleteevent($id = "") {
        if (!isset($id) || $id == "")
            redirect('user');
        $conds['users'] = array(0 => $this->session->userdata('user_id'));
        $input = array(
            'user_id' => $this->session->userdata('user_id'),
            'event_id' => $id
        );
        if ($this->user_model->deleteEvent($input))
            $data['mess'] = "Event bol úspešne vymazaný";
        else
            $data['mess'] = "Event NEbol úspešne vymazaný";

        $data = array('events' => $this->user_model->getEvents($conds),
            'events2' => isset($conds2) ? $this->user_model->getEvents($conds2) : "",
            'users' => $this->admin_model->getUsers(''),
        );

        $this->template->set('title', 'SKaP - tabuľka');
        $this->template->view("table_view", $data);
    }

    /*
     * Metoda sluziaca na import kalendara
     * 
     * 
     */

    function import() {
        if (isset($_POST['submit'])) {
            if ($meta = $this->do_upload_ics()) {
                $import = new ImEx();
                $import->importEvents($meta['file_name']);
                $data['mess'] = "Import prebehol úspešne!";
                $this->template->set('title', 'SKAP - import údajov');
                $this->template->view("import_form", $data);
                return;
            } else {
                echo $this->upload->display_errors('<p>', '</p>');
                $data['mess'] = "Nepodarilo sa nahrať ics súbor";
                $this->template->set('title', 'SKAP - import údajov');
                $this->template->view("import_form", $data);
            }
        } else {

            $this->template->set('title', 'SKAP - import údajov');
            $this->template->view("import_form");
        }
    }

    /**
     * Metoda sluziaca na export kalendara
     */
    function export() {
        $this->form_validation->set_rules('submit', 'submit', 'required');
        $data['types'] = $this->user_model->getEventTypes();
        if ($this->form_validation->run()) {
            $export = new ImEx();
            $users = $this->session->userdata('conds');
            $condition = array('teacher' => $users['users'],
                'date' => $this->session->userdata('date'));
            if ($export->exportEvents('temp/export.ics', $condition))
                redirect(base_url() . 'temp/export.ics');
            else
                $data['message'] = "Export neprebehol úspešne";


            $this->template->set('title', 'SKAP - import údajov');
            $this->template->view("export_form", $data);
        } else {
            $this->template->set('title', 'SKAP - import údajov');
            $this->template->view("export_form", $data);
        }
    }

    /**
     * funkcia sluzi na upload ics suborov na server
     * @return boolean 
     */
    function do_upload_ics() {
        $config['upload_path'] = 'temp';
        $config['allowed_types'] = '*';
        $this->load->library('upload', $config);
        if (!$this->upload->do_upload())
            return false;
        else
            return $this->upload->data();
    }

    /*
     * Metoda sluziaca na zmenu hesla pouzivatela
     */

    function changePasswd() {

        $this->form_validation->set_rules('old_pass', 'stare_heslo', 'trim|required|xss_clean');
        $this->form_validation->set_rules('pass', 'heslo', 'trim|required|xss_clean|min_length[4]');
        $this->form_validation->set_rules('pass2', 'heslo2', 'trim|required|xss_clean|matches[pass]');

        if ($this->form_validation->run()) {

            $login_data = array('username' => $this->session->userdata('username'),
                'password' => sha1($_POST['old_pass']));

            if ($this->login_model->verifyLogin($login_data)) {

                $input_data = array(
                    'user_id' => $this->session->userdata('user_id'),
                    'user_login' => array('password' => sha1($_POST['pass']), 'isAdmin' => 0)
                );

                if ($this->admin_model->editUser($input_data)) {
                    $data['mess'] = "Heslo bolo úspešne zmenené!";
                } else {
                    $data['mess'] = "Heslo sa Nepodarilo zmeniť.";
                }
            } else {
                $data['mess'] = "Staré heslo bolo nesprávne zadané!";
            }
            $this->template->set('title', 'SKAP - zmena hesla');
            $this->template->view("changePasswd_form", $data);
        } else {
            $this->template->set('title', 'SKAP - zmena hesla');
            $data = "";
            $this->template->view("changePasswd_form", $data);
        }
    }

    /**
     * Metóda zobrazí používateľskú príručku
     */
    function help() {
        $this->template->set('title', 'SKAP - používateľská príručka');
        $this->template->view('user_help_view');
    }

}

